
package com.device.idea.wbservicesdk.demo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.device.idea.wbservicesdk.demo.sdkInit.SdkPresenter;
import com.device.idea.whiteboardservice.entity.LayoutInfo;
import com.device.idea.whiteboardservicesdk.Callback;
import com.device.idea.whiteboardservicesdk.CloseCallback;
import com.device.idea.whiteboardservicesdk.IWhiteboardAppEventHandler;
import com.device.idea.whiteboardservicesdk.entity.AppInfo;
import com.device.idea.whiteboardservicesdk.entity.StopStatus;
import com.device.idea.whiteboardservicesdk.entity.WindowStatus;

import java.lang.reflect.Method;

public class WbServiceDemoActivity extends Activity implements IWhiteboardAppEventHandler {
    private static final String TAG = WbServiceDemoActivity.class.getSimpleName();

    private static final int REQUEST_CODE = 1;

    private WindowManager windowManager;

    private WindowManager.LayoutParams layoutParams;

    private Button openButton;

    private Button version;

    private Button serviceVersion;

    private Button platformVersion;

    // 标记打开或者关闭
    private Boolean isOpen = true;

    // 获取白板的componentName
    private ComponentName componentName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.whole_screen);
        if (!isCanDrawOverlays(this)) {
            requestAlertWindowPermission();
        }
        initSdk();
        initVersionView();
        initVersionClick();
        showFloatingWindow();
    }

    // 判断权限
    private boolean isCanDrawOverlays(Context context) {
        Boolean result = true;
        try {
            Class clazz = Settings.class;
            Method canDrawOverlays = clazz.getDeclaredMethod("canDrawOverlays", Context.class);
            result = (Boolean) canDrawOverlays.invoke(null, context);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return result;
    }

    // 申请权限
    private void requestAlertWindowPermission() {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, this + " onDestroy");
        windowManager.removeView(openButton);
        SdkPresenter.destroy();
        super.onDestroy();
    }

    private void initSdk() {
        AppInfo appInfo = new AppInfo(getPackageName(), getFilesDir().getPath());
        SdkPresenter.initSdkController(this, appInfo, this);
        SdkPresenter.setUiInstance(this);
    }

    private void initView() {
        openButton = new Button(this);
        openButton.setText(R.string.open);
        // 更新悬浮窗位置
        openButton.setOnTouchListener(new FloatingOnTouchListener());
        openButton.setOnClickListener(view -> {
            if (isOpen) {
                SdkPresenter.openAnnotation(new Callback() {
                    @Override
                    public void onSuccess(Object o) {
                        Log.i(TAG, "open success");
                    }

                    @Override
                    public void onFailed(int i, String s) {
                        Log.i(TAG, "open fail");
                    }
                });
                isOpen = false;
                openButton.setText(R.string.close);
            } else {
                SdkPresenter.closeBoard(componentName, new CloseCallback<Void>() {
                    @Override
                    public void onSuccess(Void unused) {
                        Log.i(TAG, "close success");
                    }

                    @Override
                    public void onInterrupted(Void unused) {
                        Log.i(TAG, "close interrupted");
                    }

                    @Override
                    public void onFailed(int i, String s) {
                        Log.i(TAG, "close fail");
                    }
                });
                isOpen = true;
                openButton.setText(R.string.open);
            }
        });
    }

    private void initVersionView() {
        version = findViewById(R.id.version);
        serviceVersion = findViewById(R.id.service_version);
        platformVersion = findViewById(R.id.platform_version);
    }

    private void initVersionClick() {
        version.setOnClickListener(view -> {
            String versionResult = SdkPresenter.getSdkVersion();
            Toast.makeText(getApplication(), versionResult, Toast.LENGTH_SHORT).show();
        });
        serviceVersion.setOnClickListener(view -> {
            String versionResult = SdkPresenter.getServerVersion();
            Toast.makeText(getApplication(), versionResult, Toast.LENGTH_SHORT).show();
        });
        platformVersion.setOnClickListener(view -> {
            String versionResult = SdkPresenter.getPlatformVersion();
            Toast.makeText(getApplication(), versionResult, Toast.LENGTH_SHORT).show();
        });
    }

    // 调用该方法，可创建一个悬浮窗显示于屏幕之上
    private void showFloatingWindow() {
        initView();
        layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT, 0, 0, PixelFormat.TRANSPARENT);
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 && Settings.canDrawOverlays(this)) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }

        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        layoutParams.x = 300;
        layoutParams.y = 300;
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        windowManager.addView(openButton, layoutParams);
    }

    @Override
    public void onWindowStatusChangedNotify(ComponentName componentName, LayoutInfo layoutInfo,
        WindowStatus windowStatus) {
        Log.i(TAG, "componentName ==" + componentName);
        this.componentName = componentName;
        runOnUiThread(() -> {
            if (windowStatus.equals(WindowStatus.STATUS_CLOSE)) {
                openButton.setText(R.string.open);
                isOpen = true;
            } else if (windowStatus.equals(WindowStatus.STATUS_OPEN)) {
                openButton.setText(R.string.close);
                isOpen = false;
            } else {
                Log.i(TAG, "service pause");
            }
        });

    }

    @Override
    public void onShareBoardStopNotify(ComponentName componentName, StopStatus stopStatus) {
        Log.i(TAG, "onShareBoardStopNotify success");
    }

    @Override
    public void onError(int i, String s) {

    }

    @Override
    public void onServiceConnected() {
        Log.i(TAG, "onServiceConnected success");
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }

    // 悬浮窗更新
    private class FloatingOnTouchListener implements View.OnTouchListener {
        private int startX;

        private int startY;

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    startX = (int) event.getRawX();
                    startY = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int nowX = (int) event.getRawX();
                    int nowY = (int) event.getRawY();
                    int movedX = nowX - startX;
                    int movedY = nowY - startY;
                    startX = nowX;
                    startY = nowY;
                    layoutParams.x = layoutParams.x + movedX;
                    layoutParams.y = layoutParams.y + movedY;

                    // 更新悬浮窗控件布局
                    windowManager.updateViewLayout(view, layoutParams);
                    break;
                default:
                    break;
            }
            return false;
        }
    }
}